<?php
import('ORG.Util.Function');
import("@.Org.Page");
import("@.Org.UserTool");
import("@.Org.CommonTool");
import("@.Plugs.Exchange");


class UserAction extends CommonAction {
	
	public function _initialize(){
		parent::_initialize();
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];
		//language
		$lang            =    L($action);
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	
	/**
	 * 空操作处理
	 * @see front/Lib/Action/CommonAction::_empty()
	 */
	public function _empty(){
		$this->redirect('/user/user_list');
	}
	
	/**
	 * 会员列表
	 * Enter description here ...
	 */
	public function user_list(){
		
		$UserModel		=	new UserModel();
		
	    $sql 			= 	"SELECT rank_id, rank_name, min_points FROM " . 'ybr_user_rank' . " ORDER BY min_points ASC ";
	    $rs 			= 	M()->query($sql);
	
	    $ranks 			= 	array();
	    foreach($ranks as $row){
	    	$ranks[$row['rank_id']] 	= 	$row['rank_name'];
	    }	    	
	    $this->assign('user_ranks',   $ranks);
	    $this->assign('user_list',    $user_list['user_list']);
	    $this->assign('filter',       $user_list['filter']);
	    $this->assign('record_count', $user_list['record_count']);
	    $this->assign('page_count',   $user_list['page_count']);
	    $this->assign('full_page',    1);
	    $this->assign('sort_user_id', '<img src="' . __PUBLIC__ . '/Image/Admin/sort_desc.gif">');	// 默认排序	
		// 用户列表
	    $sql_user_list 	= 	$UserModel->get_sql_user_list();	   
	    
		$param 		= 	array(
			'result'	=> $sql_user_list,					//分页用的数组或sql
			'listvar'	=> 'user_list',						//分页循环变量
			'listRows'	=> 10,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'User:user_list',				//ajax更新模板
		);
	    
	    $this->page_user_list($param);	    
		$this->display();
	}
	
	/**
	 +----------------------------------------------------------
	 * 分页函数 支持sql和数据集分页 sql请用 buildSelectSql()函数生成
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param array  $result 排好序的数据集或者查询的sql语句
	 * @param int    $totalRows  每页显示记录数 默认21
	 * @param string $listvar    赋给模板遍历的变量名 默认list
	 * @param string $parameter  分页跳转的参数
	 * @param string $target  分页后点链接显示的内容id名
	 * @param string $pagesId  分页后点链接元素外层id名
	 * @param string $template ajaxlist的模板名
	 * @param string $url ajax分页自定义的url
	 +----------------------------------------------------------
	 */
	public function page_user_list($param) {
		extract($param);
		/* 总记录数 */
		$flag 				= 	is_string($result);
		
		$listvar 			= 	$listvar ? $listvar : 'list';
		$listRows 			= 	$listRows? $listRows : 21;
		if ($flag){
			$totalRows		=	count(M()->query($result));
		}			
		else{
			$totalRows 		= 	($result) ? count($result) : 1;
		}
		/* 创建分页对象 */
		if ($target && $pagesId)
			$p 				=	 new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p 				= 	new Page($totalRows, $listRows, $parameter,$url);
		/* 抽取数据 */
		if ($flag) {
			$result 		.=	" LIMIT {$p->firstRow},{$p->listRows}";
			$voList 		= 	M()->query($result);
		} else {
			$voList 		= 	array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages 				= 	C('PAGE');		// 要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		/* 格式化数据 */
    	foreach($voList as $k => $value){
        	$voList[$k]['reg_time'] = local_date($GLOBALS['_CFG']['date_format'], $value['reg_time']);
    	}
		
		/* 可以使用该方法前用C临时改变配置 */
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); 		// 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		/* 分页显示  */
		$page 				= 	$p->show();		
		/* 模板赋值 */
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {					//判断ajax请求
			layout(false);
			$template 		= 	(!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
		
	/**
	 * 会员信息
	 * @param	user_id		int
	 * 
	 */
	public function user_info(){}
	
	/**
	 * 添加会员
	 * Enter description here ...
	 */
	public function add_user(){
	    $user = array(  
	    	'rank_points'   => $GLOBALS['_CFG']['register_points'],
            'pay_points'    => $GLOBALS['_CFG']['register_points'],
            'sex'           => 0,
            'credit_line'   => 0
	    );
	    /* 取出注册扩展字段 */
	    $sql 				= 	'SELECT * FROM ' . ' ybr_reg_fields ' . ' WHERE type < 2 AND display = 1 AND id != 6 ORDER BY dis_order, id';
	    $extend_info_list 	= 	M()->query($sql);
	    $this->assign('extend_info_list', $extend_info_list);	
	    $this->assign('special_ranks',    get_rank_list(true));
	    $this->assign('action',    "insert");	   
	    $this->assign('form_action',    "add_user_ok");	   
	    $this->assign('user',             $user); 
	    
	    $this->display('user_info');
	}
	
	/**
	 * 处理添加会员
	 * 
	 */
	public function add_user_ok(){
		
		$CommonModel	=	new CommonModel();		
		
	    $username 		= 	empty($_POST['username']) ? '' : trim($_POST['username']);
	    $password 		= 	empty($_POST['password']) ? '' : trim($_POST['password']);
	    $email 			= 	empty($_POST['email']) ? '' : trim($_POST['email']);
	    $sex 			= 	empty($_POST['sex']) ? 0 : intval($_POST['sex']);
	    $sex 			= 	in_array($sex, array(0, 1, 2)) ? $sex : 0;
	    $birthday 		= 	$_POST['birthdayYear'] . '-' .  $_POST['birthdayMonth'] . '-' . $_POST['birthdayDay'];
	    $rank 			= 	empty($_POST['user_rank']) ? 0 : intval($_POST['user_rank']);
	    $credit_line 	= 	empty($_POST['credit_line']) ? 0 : floatval($_POST['credit_line']);
	
	    $users 			=	& init_users();
		    
	    if (!$users->add_user($username, $password, $email)){
	        /* 插入会员数据失败 */
	        if ($users->error == ERR_INVALID_USERNAME){
	            $msg 	= 	L('username_invalid');
	        }
	        elseif ($users->error == ERR_USERNAME_NOT_ALLOW){
	            $msg 	= 	L('username_not_allow');
	        }
	        elseif ($users->error == ERR_USERNAME_EXISTS){
	            $msg 	= 	L('username_exists');
	        }
	        elseif ($users->error == ERR_INVALID_EMAIL){
	            $msg 	= 	L('email_invalid');
	        }
	        elseif ($users->error == ERR_EMAIL_NOT_ALLOW){
	            $msg 	= 	L('email_not_allow');
	        }
	        elseif ($users->error == ERR_EMAIL_EXISTS){
	            $msg 	= 	L('email_exists');
	        }
	        else{
	            //die('Error:'.$users->error_msg());
	        }
	        //sys_msg($msg, 1);
	        $this->error($msg);
	    }
	
	    /* 注册送积分 */
	    if (!empty($GLOBALS['_CFG']['register_points'])){
	        log_account_change($_SESSION['user_id'], 0, 0, $GLOBALS['_CFG']['register_points'], $GLOBALS['_CFG']['register_points'], L('register_points'));
	    }
	
	    /*把新注册用户的扩展信息插入数据库*/
	    $sql 				= 	'SELECT id FROM ' . 'ybr_reg_fields' . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   //读出所有扩展字段的id
	    $fields_arr 		= 	M()->query($sql);
			    
	    $extend_field_str 	= 	'';    //生成扩展字段的内容字符串
	    $user_id_arr 		= 	$users->get_profile_by_name($username);
	    foreach ($fields_arr AS $val){
	        $extend_field_index 	= 	'extend_field' . $val['id'];
	        if(!empty($_POST[$extend_field_index])){
	            $temp_field_content = 	strlen($_POST[$extend_field_index]) > 100 ? mb_substr($_POST[$extend_field_index], 0, 99) : $_POST[$extend_field_index];
	            $extend_field_str 	.= 	" ('" . $user_id_arr['user_id'] . "', '" . $val['id'] . "', '" . $temp_field_content . "'),";
	        }
	    }
	    $extend_field_str 	= 	substr($extend_field_str, 0, -1);
	    
	    if ($extend_field_str){//插入注册扩展数据
	        $sql 			= 	'INSERT INTO '. 'ybr_reg_extend_info' . ' (`user_id`, `reg_field_id`, `content`) VALUES' . $extend_field_str;
	        $CommonModel->query($sql);
	    }
	
	    /* 更新会员的其它信息 */
	    $other 					=  	array();
	    $other['credit_line'] 	= 	$credit_line;
	    $other['user_rank']  	= 	$rank;
	    $other['sex']        	= 	$sex;
	    $other['birthday']   	= 	$birthday;
	    $other['reg_time'] 		= 	local_strtotime(local_date('Y-m-d H:i:s'));
	
	    $other['msn'] 			= 	isset($_POST['extend_field1']) ? htmlspecialchars(trim($_POST['extend_field1'])) : '';
	    $other['qq'] 			=	isset($_POST['extend_field2']) ? htmlspecialchars(trim($_POST['extend_field2'])) : '';
	    $other['office_phone'] 	= 	isset($_POST['extend_field3']) ? htmlspecialchars(trim($_POST['extend_field3'])) : '';
	    $other['home_phone'] 	= 	isset($_POST['extend_field4']) ? htmlspecialchars(trim($_POST['extend_field4'])) : '';
	    $other['mobile_phone'] 	= 	isset($_POST['extend_field5']) ? htmlspecialchars(trim($_POST['extend_field5'])) : '';
	
	    $CommonModel->autoExecute('users', $other, 'UPDATE', "user_name = '$username'");    
	    
	    /* 记录管理员操作 */
	    admin_log($_POST['username'], 'add', 'users');	
	    //$this->success(sprintf(L('add_success'),$username),U('user/add_user'));
	}
	
	/**
	 * 编辑用户信息
	 * Enter description here ...
	 */
	public function user_edit(){
		
		$CommonModel	=	new CommonModel();
		
	    $sql 			= 	"SELECT u.user_name, u.sex, u.birthday, u.pay_points, u.rank_points, u.user_rank , u.user_money, u.frozen_money, u.credit_line, u.parent_id, u2.user_name as parent_username, u.qq, u.msn,
	    					u.office_phone, u.home_phone, u.mobile_phone".
	        				" FROM " .'ybr_users'. " u LEFT JOIN " . 'ybr_users' . " u2 ON u.parent_id = u2.user_id WHERE u.user_id='$_GET[id]'";
	
	    $row 				= 	$CommonModel->GetRow($sql);
	    $row['user_name'] 	= 	addslashes($row['user_name']);
	    $users  			=	& init_users();
	    
	    $user   			= 	$users->get_user_info($row['user_name']);
	
	    $sql 				= 	"SELECT u.user_id, u.sex, u.birthday, u.pay_points, u.rank_points, u.user_rank , u.user_money, u.frozen_money, u.credit_line, u.parent_id, u2.user_name as parent_username, u.qq, u.msn,
	    						u.office_phone, u.home_phone, u.mobile_phone".
	        					" FROM " .'ybr_users' . " u LEFT JOIN " . 'ybr_users' . " u2 ON u.parent_id = u2.user_id WHERE u.user_id='$_GET[id]'";
	
	    $row 				= 	$CommonModel->GetRow($sql);
	
	    if ($row){
	        $user['user_id']        		= 	$row['user_id'];
	        $user['sex']           			= 	$row['sex'];
	        $user['birthday']      			= 	date($row['birthday']);
	        $user['pay_points']  			= 	$row['pay_points'];
	        $user['rank_points']  			= 	$row['rank_points'];
	        $user['user_rank']      		= 	$row['user_rank'];
	        $user['user_money']     		= 	$row['user_money'];
	        $user['frozen_money']   		= 	$row['frozen_money'];
	        $user['credit_line']    		= 	$row['credit_line'];
	        $user['formated_user_money'] 	= 	price_format($row['user_money']);
	        $user['formated_frozen_money'] 	= 	price_format($row['frozen_money']);
	        $user['parent_id']      		= 	$row['parent_id'];
	        $user['parent_username']		= 	$row['parent_username'];
	        $user['qq']             		= 	$row['qq'];
	        $user['msn']            		= 	$row['msn'];
	        $user['office_phone']   		= 	$row['office_phone'];
	        $user['home_phone']     		= 	$row['home_phone'];
	        $user['mobile_phone']   		= 	$row['mobile_phone'];
	    }
	    else{
	          $link[] = array('text' => $_LANG['go_back'], 'href'=>'users.php?act=list');
	          sys_msg($_LANG['username_invalid'], 0, $links);
	//        $user['sex']            = 0;
	//        $user['pay_points']     = 0;
	//        $user['rank_points']    = 0;
	//        $user['user_money']     = 0;
	//        $user['frozen_money']   = 0;
	//        $user['credit_line']    = 0;
	//        $user['formated_user_money'] = price_format(0);
	//        $user['formated_frozen_money'] = price_format(0);
	     }
	
	    /* 取出注册扩展字段 */
	    $sql 				= 	'SELECT * FROM ' . 'ybr_reg_fields' . ' WHERE type < 2 AND display = 1 AND id != 6 ORDER BY dis_order, id';
	    $extend_info_list 	= 	$CommonModel->query($sql);
	
	    $sql 				= 	'SELECT reg_field_id, content ' .
	           					'FROM ' . 'ybr_reg_extend_info' .
	           					" WHERE user_id = $user[user_id]";
	    $extend_info_arr 	= 	$CommonModel->query($sql);
	
	    $temp_arr 			= 	array();
	    foreach ($extend_info_arr AS $val){
	        $temp_arr[$val['reg_field_id']] = $val['content'];
	    }
	
	    foreach ($extend_info_list AS $key => $val){
	        switch ($val['id']){
	            case 1:     $extend_info_list[$key]['content'] = $user['msn']; break;
	            case 2:     $extend_info_list[$key]['content'] = $user['qq']; break;
	            case 3:     $extend_info_list[$key]['content'] = $user['office_phone']; break;
	            case 4:     $extend_info_list[$key]['content'] = $user['home_phone']; break;
	            case 5:     $extend_info_list[$key]['content'] = $user['mobile_phone']; break;
	            default:    $extend_info_list[$key]['content'] = empty($temp_arr[$val['id']]) ? '' : $temp_arr[$val['id']] ;
	        }
	    }
	
	    $this->assign('extend_info_list', $extend_info_list);
	
	    /* 当前会员推荐信息 */
	    $affiliate 	= 	unserialize($GLOBALS['_CFG']['affiliate']);
	    $this->assign('affiliate', $affiliate);
	
	    empty($affiliate) && $affiliate = array();
	
	    if(empty($affiliate['config']['separate_by'])){
	        //推荐注册分成
	        $affdb 			= 	array();
	        $num 			= 	count($affiliate['item']);
	        $up_uid 		= 	"'$_GET[id]'";
	        for ($i = 1 ; $i <=$num ;$i++){
	            $count 		= 	0;
	            if ($up_uid){
	                $sql 	= 	"SELECT user_id FROM " . 'ybr_users' . " WHERE parent_id IN($up_uid)";
	                $query 	= 	$CommonModel->query($sql);
	                $up_uid = 	'';
	                foreach($query as $rt){
	                	$up_uid 	.= 	$up_uid ? ",'$rt[user_id]'" : "'$rt[user_id]'";
	                    $count++;
	                }
	            }
	            $affdb[$i]['num'] = $count;
	        }
	        if ($affdb[1]['num'] > 0){
	            $this->assign('affdb', $affdb);
	        }
	    }
	
	    $this->assign('user',             $user);
	    $this->assign('action',      'user_edit_ok');
	    $this->assign('form_action',      'update');
	    $this->assign('special_ranks',    get_rank_list(true));		
		
		$this->display("user_info");
	}
	
	/**
	 * 处理修改会员信息
	 * Enter description here ...
	 */
	public function user_edit_ok(){
		
		$CommonModel	=	new CommonModel();
		
	    $username 		= 	empty($_POST['username']) ? '' : trim($_POST['username']);
	    $password 		= 	empty($_POST['password']) ? '' : trim($_POST['password']);
	    $email	 		= 	empty($_POST['email']) ? '' : trim($_POST['email']);
	    $sex 			= 	empty($_POST['sex']) ? 0 : intval($_POST['sex']);
	    $sex 			= 	in_array($sex, array(0, 1, 2)) ? $sex : 0;
	    $birthday 		= 	$_POST['birthdayYear'] . '-' .  $_POST['birthdayMonth'] . '-' . $_POST['birthdayDay'];
	    $rank 			= 	empty($_POST['user_rank']) ? 0 : intval($_POST['user_rank']);
	    $credit_line 	= 	empty($_POST['credit_line']) ? 0 : floatval($_POST['credit_line']);
	
	    $users  		=	& init_users();
	
	    if (!$users->edit_user(array('username'=>$username, 'password'=>$password, 'email'=>$email, 'gender'=>$sex, 'bday'=>$birthday ), 1)){
	        if ($users->error == ERR_EMAIL_EXISTS){
	            $msg 	= 	L('email_exists');
	        }
	        else{
	            $msg 	= 	L('edit_user_failed');
	        }
	        $this->error($msg);
	    }
	    
	    if(!empty($password)){
				$sql	=	"UPDATE " . 'ybr_users' . "SET `ec_salt`='0' WHERE user_name= '".$username."'";
				$CommonModel->query($sql);
		}
	    /* 更新用户扩展字段的数据 */
	    $sql 			= 	'SELECT id FROM ' . 'ybr_reg_fields' . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   //读出所有扩展字段的id
	    $fields_arr 	= 	$CommonModel->query($sql);
	    $user_id_arr 	= 	$users->get_profile_by_name($username);
	    $user_id 		= 	$user_id_arr['user_id'];
	
	    foreach ($fields_arr AS $val){       //循环更新扩展用户信息
	        $extend_field_index 		= 	'extend_field' . $val['id'];
	        if(isset($_POST[$extend_field_index])){
	            $temp_field_content 	= 	strlen($_POST[$extend_field_index]) > 100 ? mb_substr($_POST[$extend_field_index], 0, 99) : $_POST[$extend_field_index];
	
	            $sql					= 	'SELECT * FROM ' . 'ybr_reg_extend_info' . "  WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'";
	            if ($CommonModel->getOne($sql)){      //如果之前没有记录，则插入
	            
	                $sql 				= 	'UPDATE ' . 'ybr_reg_extend_info' . " SET content = '$temp_field_content' WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'";
	            }
	            else{
	                $sql 				= 	'INSERT INTO '. 'ybr_reg_extend_info' . " (`user_id`, `reg_field_id`, `content`) VALUES ('$user_id', '$val[id]', '$temp_field_content')";
	            }
	            $CommonModel->query($sql);
	        }
	    }
		
	    /* 更新会员的其它信息 */
	    $other 					=  	array();
	    $other['credit_line'] 	= 	$credit_line;
	    $other['user_rank'] 	= 	$rank;
	
	    $other['msn'] 			= 	isset($_POST['extend_field1']) ? htmlspecialchars(trim($_POST['extend_field1'])) : '';
	    $other['qq'] 			= 	isset($_POST['extend_field2']) ? htmlspecialchars(trim($_POST['extend_field2'])) : '';
	    $other['office_phone'] 	=	isset($_POST['extend_field3']) ? htmlspecialchars(trim($_POST['extend_field3'])) : '';
	    $other['home_phone'] 	= 	isset($_POST['extend_field4']) ? htmlspecialchars(trim($_POST['extend_field4'])) : '';
	    $other['mobile_phone'] 	= 	isset($_POST['extend_field5']) ? htmlspecialchars(trim($_POST['extend_field5'])) : '';
	
	    $CommonModel->autoExecute('users', $other, 'UPDATE', "user_name = '$username'");	
	    /* 记录管理员操作 */
	    admin_log($username, 'edit', 'users');
			
	    $this->success("操作成功",U('user/user_list'));
	}
	
	/**
	 * 删除用户
	 * Enter description here ...
	 */
	public function remove(){
		
		$CommonModel	=	new CommonModel();
	    $sql 			= 	"SELECT user_name FROM " . 'ybr_users' . " WHERE user_id = '" . $_GET['id'] . "'";
	    $username 		= 	$CommonModel->getOne($sql);
	    /* 通过插件来删除用户 */
	    $users 			=	& init_users();
	    $users->remove_user($username); //已经删除用户所有数据
	
	    /* 记录管理员操作 */
	    admin_log(addslashes($username), 'remove', 'users');	    
	    $this->success(sprintf(L('remove_success'), $username),U('user/user_list'));	
	}
		
	/**
	 * 会员订单
	 * Enter description here ...
	 * 
	 */
	public function users_order(){
		
	}
		
	/**
	 * 用户排名详细信息
	 * Enter description here ...
	 */
	public function user_rank_info(){
			
	}
	
	/**
	 * 会员地址列表
	 * Enter description here ...
	 */
	public function user_address_list(){		
		
		$id 		= 	isset($_GET['id']) ? intval($_GET['id']) : 0;
	    $sql 		= 	"SELECT a.*, c.region_name AS country_name, p.region_name AS province, ct.region_name AS city_name, d.region_name AS district_name ".
	           			" FROM " .'ybr_user_address'. " as a ".
	           			" LEFT JOIN " . 'ybr_region' . " AS c ON c.region_id = a.country " .
	           			" LEFT JOIN " . 'ybr_region' . " AS p ON p.region_id = a.province " .
	           			" LEFT JOIN " . 'ybr_region' . " AS ct ON ct.region_id = a.city " .
	           			" LEFT JOIN " . 'ybr_region' . " AS d ON d.region_id = a.district " .
	           			" WHERE user_id='$id'";
	    $address 	= 	M()->query($sql);
	    $this->assign('address',          $address);	    
	    $this->display('user_address_list');	
	}
	
	/**
	 * 用户消息
	 * Enter description here ...
	 */
	public function user_account_message(){
		
	}
	
	/**
	 * 用户账户明细列表
	 * Enter description here ...
	 */
	public function user_account_list(){
				
	    $user_id 		= 	empty($_REQUEST['user_id']) ? 0 : intval($_REQUEST['user_id']);
	    
	    if ($user_id <= 0){
	        sys_msg('invalid param');
	        $this->error("invalid param");
	    }
	    $user 			= 	user_info($user_id);
	    if (empty($user)){
	        //sys_msg($_LANG['user_not_exist']);
	        $this->error(L('user_not_exist'));
	    }
	    $this->assign('user', $user);
	
	    if (empty($_REQUEST['account_type']) || !in_array($_REQUEST['account_type'],array('user_money', 'frozen_money', 'rank_points', 'pay_points'))){
	        $account_type 	= 	'';
	    }
	    else{
	        $account_type 	= 	$_REQUEST['account_type'];
	    }
	     
	    $sql_user_account_list 	= 	get_sql_accountlist($user_id, $account_type);	   
	    
		$param 		= 	array(
			'result'	=> $sql_user_account_list,					//分页用的数组或sql
			'listvar'	=> 'account_list',						//分页循环变量
			'listRows'	=> 20,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'User:user_list',				//ajax更新模板
		);
	    
	    $this->page_user_account_list($param);	
	   	$this->assign('account_type', $account_type);		   
	    $this->display('account_list');
	}
	
	/**
	 * 账户明细列表分页
	 * Enter description here ...
	 */
	public function page_user_account_list($param){
		extract($param);
		//总记录数
		$flag 		= 	is_string($result);
		
		$listvar 	= 	$listvar ? $listvar : 'list';
		$listRows 	= 	$listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		// 格式化数据
    	foreach($voList as $k => $row){
        	$voList[$k]['change_time'] = local_date($GLOBALS['_CFG']['time_format'], $row['change_time']);
    	}    	
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}		
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}	
	
	/**
	 * 调节会员账户
	 * Enter description here ...
	 */
	public function adjust_user_account(){
		$this->display("account_info");
	}
	
	/**
	 * 用户账户验证
	 * Enter description here ...
	 */
	public function user_account_check(){
		
	}
	
	/**
	 * 用户等级
	 * Enter description here ...
	 */
	public function user_rank(){		
		$ranks 		= 	array();
	    $ranks 		= 	M()->query("SELECT * FROM " .'ybr_user_rank');		
	    $this->assign('user_ranks',   $ranks);	
		$this->display();
	}
	
	/**
	 * 添加会员等级列表
	 * Enter description here ...
	 */
	public function add_user_rank(){

	    $rank['rank_id']      = 0;
	    $rank['rank_special'] = 0;
	    $rank['show_price']   = 1;
	    $rank['min_points']   = 0;
	    $rank['max_points']   = 0;
	    $rank['discount']     = 100;	
	    $form_action          = 'insert';		
	    $this->assign('rank',        $rank);
	    $this->assign('form_action', $form_action);	
	    $this->assign('action', 'add_user_rank_ok');	
	    $this->assign('help_open', 1);	
	    // 会员等级的权限	    
		$this->display('user_rank_info');
	}
	
	/**
	 * 处理添加会员等级列表
	 * Enter description here ...
	 */
	public function add_user_rank_ok(){
		
		$UserModel				=	new UserModel();
		
	    $special_rank 			=  	isset($_POST['special_rank']) ? intval($_POST['special_rank']) : 0;
	    $_POST['min_points'] 	= 	empty($_POST['min_points']) ? 0 : intval($_POST['min_points']);
	    $_POST['max_points'] 	= 	empty($_POST['max_points']) ? 0 : intval($_POST['max_points']);
	
	    /* 检查是否存在重名的会员等级 */
	    if (!$UserModel->is_only('rank_name', trim($_POST['rank_name']))){
	        //sys_msg(sprintf($_LANG['rank_name_exists'], trim($_POST['rank_name'])), 1);
	        $this->error(sprintf(L('rank_name_exists'), trim($_POST['rank_name'])));
	    }
	
	    /* 非特殊会员组检查积分的上下限是否合理 */
	    if ($_POST['min_points'] >= $_POST['max_points'] && $special_rank == 0){
	        //sys_msg($_LANG['js_languages']['integral_max_small'], 1);
	        $this->error("积分上限必须大于积分下限");
	    }
	
	    /* 特殊等级会员组不判断积分限制 */
	    if ($special_rank == 0){
	        /* 检查下限制有无重复 */
	        if (!$UserModel->is_only('min_points', intval($_POST['min_points']))){
	            //sys_msg(sprintf($_LANG['integral_min_exists'], intval($_POST['min_points'])));
	            $this->error( sprintf( "已经存在一个等级积分下限为 %d 的会员等级", intval( $_POST['min_points'] ) ) );
	        }
	    }
	
	    /* 特殊等级会员组不判断积分限制 */
	    if ($special_rank == 0){
	        /* 检查上限有无重复 */
	        if (!$UserModel->is_only('max_points', intval($_POST['max_points']))){
	            //sys_msg(sprintf($_LANG['integral_max_exists'], intval($_POST['max_points'])));
	            $this->error(sprintf("已经存在一个等级积分上限为 %d 的会员等级", intval($_POST['max_points'])));
	        }
	    }
	
	    $sql 	= 	"INSERT INTO " . 'ybr_user_rank' ."( ".
	                "rank_name, min_points, max_points, discount, special_rank, show_price".
	            	") VALUES (".
	                "'$_POST[rank_name]', '" .intval($_POST['min_points']). "', '" .intval($_POST['max_points']). "', ".
	                "'$_POST[discount]', '$special_rank', '" .intval($_POST['show_price']). "')";
	    M()->query($sql);
	
	    /* 管理员日志 */
	    admin_log(trim($_POST['rank_name']), 'add', 'user_rank');
	    //clear_cache_files(); // 清除缓存
		$this->success("操作成功",U('user/user_rank'));
	}
	
	/**
	 * 会员留言
	 * Enter description here ...
	 */
	public function msg_list(){
		
		$lang_msg_type		=	L('msg_type');	// 留言类型		
	    $sql_msg_list 		= 	get_sql_msg_list();
		
		$param 		= 	array(
			'result'	=> $sql_msg_list,					//分页用的数组或sql
			'listvar'	=> 'msg_list',						//分页循环变量
			'listRows'	=> 20,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'User:msg_list',				//ajax更新模板
		);
		$this->page_msg_list($param);
		
		$this->assign("msg_type",$lang_msg_type);
		$this->assign('sort_msg_id', '<img src="' . __PUBLIC__ . '/Image/Admin/sort_desc.gif">'); // 默认排序字段
		$this->display();
	}
	
	/**
	 * 会员留言分页
	 * Enter description here ...
	 */
	public function page_msg_list($param){
		extract($param);
		//总记录数
		$flag 			= 	is_string($result);
		
		$listvar	 	= 	$listvar ? $listvar : 'list';
		$listRows 		= 	$listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows 	= 	($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p 			= 	new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p 			= 	new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result 	.= 	" LIMIT {$p->firstRow},{$p->listRows}";
			$voList 	= 	M()->query($result);
		} else {
			$voList 	= 	array_slice($result, $p->firstRow, $p->listRows);
		}
		
		$pages 			= 	C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		// 格式化数据
		$CommonModel	=	new CommonModel();
		$lang_msg_type	=	L('msg_type');	// 留言类型		
	    foreach ($voList AS $key => $value){   
    		if($value['order_id'] > 0){
        	    $voList[$key]['order_sn'] 	= 	$CommonModel->getOne("SELECT order_sn FROM " . 'ybr_order_info' ." WHERE order_id= " .$value['order_id']);
        	}
        	$voList[$key]['msg_time'] 		= 	local_date($GLOBALS['_CFG']['time_format'], $value['msg_time']);
        	$voList[$key]['msg_type'] 		= 	$lang_msg_type[$value['msg_type']];
    	}
    	
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page 			= 	$p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template 	= 	(!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * 查看会员留言具体内容
	 * Enter description here ...
	 */
	public function view_msg(){
				
		$this->assign('send_fail',   !empty($_REQUEST['send_ok']));
	    $this->assign('msg',         get_feedback_detail(intval($_REQUEST['id'])));	
	    $this->display('msg_info');
	}
	
	/**
	 * 回复留言
	 * Enter description here ...
	 */
	public function reply_msg(){
		
		$CommonModel	=	new CommonModel();
				
		if (empty($_REQUEST['parent_id'])){
	        $sql 		= 	"INSERT INTO " . 'ybr_feedback' . " (msg_title, msg_time, user_id, user_name , ".
	                    	"user_email, parent_id, msg_content) ".
	                		"VALUES ('reply', '".gmtime()."', '".$_SESSION['admin_id']."', ".
	                    	"'".$_SESSION['admin_name']."', '".$_POST['user_email']."', ".
	                    	"'".$_REQUEST['msg_id']."', '".$_POST['msg_content']."') ";
	        $CommonModel->query($sql);
	    }
	    else{
	        $sql 		= 	"UPDATE ".'ybr_feedback' . " SET user_email = '".$_POST['user_email']."', msg_content='".$_POST['msg_content']."', msg_time = '".gmtime()."' WHERE msg_id = '".$_REQUEST['parent_id']."'";
	        $CommonModel->query($sql);
	    }
	
	    /* 邮件通知处理流程 */
	    if (!empty($_POST['send_email_notice']) or isset($_POST['remail'])){
	        //获取邮件中的必要内容
	        $sql 		= 	'SELECT user_name, user_email, msg_title, msg_content ' .
	               			'FROM ' .'ybr_feedback' .
	               			" WHERE msg_id ='$_REQUEST[msg_id]'";
	        $message_info 	= 	$CommonModel->getRow($sql);
	
	        /* 设置留言回复模板所需要的内容信息
	        $template    	= 	get_mail_template('user_message');
	        $message_content = $message_info['msg_title'] . "\r\n" . $message_info['msg_content'];
	
	        $this->assign('user_name',   $message_info['user_name']);
	        $this->assign('message_note', $_POST['msg_content']);
	        $this->assign('message_content', $message_content);
	        $this->assign('shop_name',   "<a href='".$ecs->url()."'>" . $_CFG['shop_name'] . '</a>');
	        $this->assign('send_date',   date('Y-m-d'));	
	        $content = $this->fetch('str:' . $template['template_content']);
	
	        // 发送邮件 
	        if (send_mail($message_info['user_name'], $message_info['user_email'], $template['template_subject'], $content, $template['is_html'])){
	            $send_ok = 0;
	        }
	        else{
	            $send_ok = 1;
	        }*/	        
	    }
		$this->success("操作成功",U('user/view_msg') . '?id=' . $_REQUEST['msg_id']);		
	}
	
	/**
	 * 删除留言
	 * Enter description here ...
	 */
	public function del_msg(){
		
		$CommonModel	=	new CommonModel();
		
	    $msg_id 		= 	intval($_REQUEST['id']);	   	
	    $exc			=	new Exchange("ybr_feedback", null, 'msg_id', 'msg_title');	    
	    $msg_title 		= 	$exc->get_name($msg_id);
	    $img 			= 	$exc->get_name($msg_id, 'message_img');	    
	    
	    if ( is_array($exc->drop($msg_id)) ){
	        /* 删除图片 */
	        if (!empty($img)){
	             //@unlink(ROOT_PATH. DATA_DIR . '/feedbackimg/'.$img);
	        }
	        $sql 		= 	"DELETE FROM " . 'ybr_feedback' . " WHERE parent_id = '$msg_id' LIMIT 1";
	        $CommonModel->query($sql);
	        // 记录删除留言	
	        admin_log(addslashes($msg_title), 'remove', 'message');	        
	        $this->success("操作成功",U('user/msg_list'));
	    }
	    else{
	       	$this->error("操作失败");	        
	    }
	}
	
	/**
	 * 账户列表
	 * Enter description here ...
	 */
	public function account_list(){
		
		$CommonModel	=	new CommonModel();
		
	    /* 指定会员的ID为查询条件 */
	    $user_id 		= 	!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
	
	    /* 获得支付方式列表 */
	    $payment 		= 	array();
	    $sql 			= 	"SELECT pay_id, pay_name FROM " . 'ybr_payment' . " WHERE enabled = 1 AND pay_code != 'cod' ORDER BY pay_id";
	    $res 			= 	$CommonModel->query($sql);
		
	    foreach($res as $row){
	    	$payment[$row['pay_name']] = $row['pay_name'];
	    }
	
	    /* 模板赋值 */
	    if (isset($_REQUEST['process_type'])){
	        $this->assign('process_type_' . intval($_REQUEST['process_type']), 'selected="selected"');
	    }
	    if (isset($_REQUEST['is_paid'])){
	        $this->assign('is_paid_' . intval($_REQUEST['is_paid']), 'selected="selected"');
	    }
	    $this->assign('ur_here',       '充值和提现申请');
	    $this->assign('id',            $user_id);
	    $this->assign('payment_list',  $payment);
	    $this->assign('action_link',   array('text' =>L('surplus_add'), 'href'=>'user_account.php?act=add'));
	
	    $sql_account_list 		= 	get_sql_account_list();
	    
	    $param 			= 	array(
			'result'	=> $sql_account_list,					//分页用的数组或sql
			'listvar'	=> 'account_list',						//分页循环变量
			'listRows'	=> 20,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'User:msg_list',				//ajax更新模板
		);
	    $this->page_account_list($param);	    
	    $this->display('user_account_list');		
	}
		
	/**
	 * 账户分页
	 * Enter description here ...
	 */
	public function page_account_list($param){
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		// 格式化数据
	    foreach ($voList AS $key => $value){
    	    $voList[$key]['surplus_amount']       = 	price_format(abs($value['amount']), false);
        	$voList[$key]['add_date']             = 	local_date($GLOBALS['_CFG']['time_format'], $value['add_time']);
        	$voList[$key]['process_type_name']    = 	L('surplus_type_' . $value['process_type']);
     	}
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;	
	}
	
	/**
	 * 移除用户
	 * Enter description here ...
	 * 
	 */
	public function remove_user_rank(){		
		import('@.Plugs.Exchange');
		$exc 			= 	new exchange( "ybr_user_rank", $db, 'rank_id', 'rank_name' );
		$exc_user 		= 	new exchange( "ybr_users", null, 'user_rank', 'user_rank' );
		
	    $rank_id 		= 	intval($_GET['id']);
	
	    if ($exc->drop($rank_id)){
	        /* 更新会员表的等级字段 */
	        $exc_user->edit("user_rank = 0", $rank_id);
	
	        $rank_name 	= 	$exc->get_name($rank_id);
	        
	        admin_log(addslashes($rank_name), 'remove', 'user_rank');
	        //clear_cache_files();
	    }		
	    $this->success("操作成功");
	}
	
	/**
	 * 为用户分配权限
	 * Enter description here ...
	 */
	public function allot_user_access(){
		$id                 =  	$this->_get('id');
		//用户
		$UserModel      	=  	new Model('Users'); 
		$Role_UserModel 	=  	new Model('RoleUser'); 
		$user               =  	$UserModel->field('user_id,user_name')->where('user_id=' . $id)->find();

		//当前用户权限
		$role_user_info		 =		$Role_UserModel->field('ybr_role.name role_name')
												   ->join('ybr_role on ybr_role.id=ybr_role_user.role_id')
												   ->where('ybr_role_user.user_id=' . $id)->find();
						
		//用户组列表
		$Role                =     new Model('Role');
		$roleList            =     $Role->field('id,name')->where('invalid=0')->select();
				
		$this->assign('user',$user);
		$this->assign('roleList',$roleList);
		$this->assign('role_user_info',$role_user_info);
		$this->display();
	}
	
	/**
	 * 处理为用户分配权限
	 * Enter description here ...
	 */
	public function allot_user_access_ok(){
		
		$Role_UserModel         =     new Model('RoleUser');
		$user_name         			 =     $this->_post('user_name');
		if($user_name == 'admin'){
			$this->error('你没有操作此用户的权限',U('user/user_list'));
			return;
		}
		unset($_POST['user_name']);
		//判断用户是否已经分配了权限
		$role_id            =     $_POST['role_id'];
		$user_id            =     $_POST['user_id'];
		$con                =     "user_id=" . $user_id;
		$isExist            =     $Role_UserModel->where($con)->find();
		
		$result             =     false;
		$url                =     U('user/user_list');
		
		if($isExist){//是,则更新		
			$result         =     $Role_UserModel->where("user_id=" . $user_id)->save($_POST);
		}
		else{//否,则添加
			$datas			=	  $_POST;
			$datas['ctime']	=	  time();
			$result         =     $Role_UserModel->add($_POST);
		}
		
		if($result)
			$this->success('操作成功',$url);
		else
			$this->error('操作失败',$url);
	}
	
	/**
	 * 会员资产管理
	 * Enter description here ...
	 * 
	 */
	public function moneymanage(){
		t('功能尚未开发...<a href="javascript:location.href=history.go();">返回</a>');
	}
	
	
	
	
	
	
	
	
	
	
}